package org.aileen.blog.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aileen.blog.utils.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 * 用于验证用户登录状态
 * 如果用户未登录,则拦截请求,返回401状态码
 */

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证Token 是否合法
        String userToken = request.getHeader("user_token_header");
        log.info("从header中获取信息 , token : "+ userToken);
        Claims claims = JWTUtils.verify(userToken);
        if (claims == null) {
            //token效验失败
            response.setStatus(401);
            //自行补充
            //response.getOutputStream().write("Token不合法".getBytes());
            //response.setContentType("application/json;charset=UTF-8");
            return false; // 返回false表示请求被拦截,前端请求失败走错误处理流程error:function(error)
        }
        //token效验成功
        return true; // 返回true表示请求继续执行,前端请求成功走成功处理流程success:function(result)
    }
}
